package org.geektimes.rest.client;

import org.geektimes.rest.core.DefaultResponse;

import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.Map;

/**
 * @author lanxing
 * @date 2021/3/30 16:45
 */
public abstract class AbstractHttpMethodInvocation {

    /**
     * 设置头信息
     * @param connection
     * @param headers
     */
    protected void setRequestHeaders(HttpURLConnection connection, MultivaluedMap<String, Object> headers) {
        for (Map.Entry<String, List<Object>> entry : headers.entrySet()) {
            String headerName = entry.getKey();
            for (Object headerValue : entry.getValue()) {
                connection.setRequestProperty(headerName, headerValue.toString());
            }
        }
    }

    /**
     * 构建Response
     * @param connection
     * @return
     * @throws IOException
     */
    protected Response buildResponse(HttpURLConnection connection) throws IOException {
        int statusCode = connection.getResponseCode();
        DefaultResponse response = new DefaultResponse();
        response.setConnection(connection);
        response.setStatus(statusCode);
        return response;
    }

}
